package net.bbtang.website.filter;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

public  class Test {
	
	 public static String createToken() throws Exception{  
		 
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 
		 
	        Map<String, Object> map = new HashMap<String, Object>();  
	        map.put("alg", "HS256");  
	        map.put("typ", "JWT");  
	        String token = JWT.create()  
	        		
	        		.withIssuer("zx")
	        		//.withIssuedAt(sdf.parse("2018-01-11"))
	                //.withExpiresAt(sdf.parse("2017-04-13 17:29:00"))
	                //.withNotBefore(sdf.parse("2017-01-11"))
	        		.withHeader(map)//header  
	                .withClaim("name", "zwz")//payload  
	                .withClaim("age", "18")  
	                .sign(Algorithm.HMAC256("secret"));//加密  
	        return token;  
	} 
	 
    public static void verifyToken(String token,String key) throws Exception{  
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key))  
        		.acceptLeeway(60)
                .build();   
            DecodedJWT jwt = verifier.verify(token);  
            Map<String, Claim> claims = jwt.getClaims();  
            System.out.println(claims.get("name").asString());  
    }  
	
	
	public static void main(String[] args) throws Exception {
		String token = Test.createToken();
		System.out.println(token);
		
		
//		    DecodedJWT jwt = JWT.decode(token);
//		    System.out.println(jwt.getAlgorithm());
//		    System.out.println(jwt.get);
//		    System.out.println(jwt.getClaims().get("name").asString());
		
		
		Test.verifyToken(token,"secret");
		
		
		
	}

}
